package com.zxb.core.auth;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.zxb.core.util.TokenUtil;
import com.zxb.core.common.Req;
import com.zxb.core.common.exception.E;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Zxb
 */
@Component
@Slf4j
public class AuthValidator {
    /**
     * 5分钟
     */
    public static final Long OVERTIME_LIMIT = 300000L;
    public static final Map<String, String> appMap = new LinkedHashMap<>();

    static {
        String appKey = "zxb0329";
        String appSecret = "pwd0329";
        log.info("appKey:" + appKey);
        log.info("appSecret:" + appSecret);
        appMap.put(appKey, appSecret);
    }

    public void hasAccessToken() {
        String accessToken = Req.getHeader("accessToken");
        if (StrUtil.isEmpty(accessToken)) {
            E.NO_SAFE_TOKEN.happen();
        }
        String result = TokenUtil.validateSafeToken(accessToken);
        if (result == null) {
            E.BAD_SAFE_TOKEN.happen();
        }
        String[] arr = result.split(":");
        if (!appMap.containsKey(arr[0]) || !appMap.get(arr[0]).equals(arr[1])) {
            E.BAD_SAFE_TOKEN.happen();
        }
    }

    public void safe() {
        String appKey = Req.getString("appKey");
        String appSecret = Req.getString("appSecret");
        String random = Req.getString("random");
        Long timestamp = Long.valueOf(Req.getString("timestamp"));
        String sign = Req.getString("sign");

        Boolean hasApp = appMap.containsKey(appKey)
                && appMap.get(appKey).equals(appSecret);

        if (!hasApp) {
            E.UN_SAFE_BAD_SECRET.happen();
        }

        long currTimestamp = Calendar.getInstance().getTimeInMillis();
        boolean timestampValidResult = (currTimestamp - timestamp) < OVERTIME_LIMIT;
        if (!timestampValidResult) {
            E.UN_SAFE_TIMEOUT.happen();
        }

        String currSign = SecureUtil.md5(appSecret + random + timestamp);
        boolean signValidResult = currSign.equals(sign);
        if (!signValidResult) {
            E.UN_SAFE_BAD_SIGN.happen();
        }
    }
}
